package dev.kaayf.examples;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;

import dev.kaayf.db.UserPrefs;

public class LoginActivity extends AppCompatActivity {

    private EditText nameView, passwdView;
    private ImageButton loginAction;
    private final static String DEFAULT_PASSWORD = "123123";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_login);
        findViews();

        UserPrefs userPrefs = new UserPrefs(this);

        loginAction.setOnClickListener(view -> {
            String name = nameView.getText().toString();
            String password = passwdView.getText().toString();
            if(validateUserInputs(name,password)){
                userPrefs.setFirstLaunch();
                userPrefs.setUserName(name);
                finish();
            }
        });

    }

    private void findViews() {
        nameView = findViewById(R.id.login_layout_name);
        passwdView = findViewById(R.id.login_layout_password);
        loginAction = findViewById(R.id.login_layout_action);
    }

    private boolean validateUserInputs(String name, String password) {

        // check empty values
        if (name.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "name or password is empty!", Toast.LENGTH_SHORT).show();
            return false;
        }

        // check name length
        if (name.length() < 2) {
            nameView.setText("");
            Toast.makeText(this, "name too short", Toast.LENGTH_SHORT).show();
            return false;
        }

        // check default password
        if (!password.equals(DEFAULT_PASSWORD)) {
            passwdView.setText("");
            Toast.makeText(this, "incorrect password", Toast.LENGTH_SHORT).show();
            return false;
        }

        // welcome
        Toast.makeText(this, "Welcome, " + name, Toast.LENGTH_SHORT).show();
        return true;
    }


}